package org.adream.account.aop.aspect;

import java.io.Serializable;

import org.adream.account.aop.annotation.DataSource;
import org.adream.account.util.DataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 注解 切换数据源
 * @author sl
 *
 */
@Component
@Aspect
public class DataSourceAspect implements  Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7139330652727108459L;

	@Pointcut("execution(* org.adream.account.service..*.*(..))")
	public void pointCut() {
	}
	
	@Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
		DataSource dataSource = pjp.getTarget().getClass().getAnnotation(DataSource.class);
        if (dataSource != null) {
            //如果存在DataSource根据dataSourceName切换数据源
            String dataSourceName = dataSource.value();
            DataSourceContextHolder.setDbType(dataSourceName);
        }
        Object obj = pjp.proceed();
        //清理dataSource
        DataSourceContextHolder.clearDbType();
        return obj;
    }
}